import { NextRequest, NextResponse } from 'next/server'

const BACKEND_URL = 'http://localhost:8232'

// 处理所有HTTP方法的通用代理函数
async function handleRequest(
  request: NextRequest,
  { params }: { params: { path: string[] } }
) {
  console.log('[API Proxy] 收到请求:', {
    method: request.method,
    url: request.url,
    params: params
  })

  try {
    // 安全获取路径参数
    if (!params || !Array.isArray(params.path)) {
      console.error('[API Proxy] Invalid path params:', params)
      return NextResponse.json(
        { error: '无效的路径参数' },
        { status: 400 }
      )
    }

    // 构建目标URL
    const path = params.path.join('/')
    const targetUrl = `${BACKEND_URL}/admin/${path}`
    
    console.log(`[API Proxy] ${request.method} ${targetUrl}`)

    // 获取查询参数
    const searchParams = request.nextUrl.searchParams
    const queryString = searchParams.toString()
    const fullTargetUrl = queryString ? `${targetUrl}?${queryString}` : targetUrl

    // 获取请求体（如果有）
    let body: string | null = null
    if (request.method !== 'GET' && request.method !== 'HEAD') {
      try {
        const text = await request.text()
        body = text || null
        console.log('[API Proxy] 请求体:', body)
      } catch (error) {
        console.warn('[API Proxy] Failed to read request body:', error)
        body = null
      }
    }

    // 复制请求头，但排除一些不需要的头
    const headers: Record<string, string> = {}
    if (request.headers) {
      request.headers.forEach((value, key) => {
        // 排除这些头，因为它们会导致问题
        const excludeHeaders = ['host', 'connection', 'origin', 'referer', 'content-length']
        if (!excludeHeaders.includes(key.toLowerCase())) {
          headers[key] = value
        }
      })
    }

    console.log('[API Proxy] 尝试连接后端:', fullTargetUrl)

    // 发送请求到后端
    const response = await fetch(fullTargetUrl, {
      method: request.method,
      headers,
      body: body || undefined,
    })

    console.log('[API Proxy] 后端响应状态:', response.status)

    // 获取响应数据
    let responseData: any
    let responseText: string
    
    try {
      responseText = await response.text()
      responseData = responseText ? JSON.parse(responseText) : {}
      console.log('[API Proxy] 后端响应数据:', responseData)
    } catch (parseError) {
      console.warn('[API Proxy] Failed to parse response as JSON:', parseError)
      responseData = responseText || ''
    }

    // 创建响应
    const nextResponse = new NextResponse(
      typeof responseData === 'string' ? responseData : JSON.stringify(responseData),
      {
        status: response.status,
        statusText: response.statusText || 'OK',
      }
    )

    // 添加CORS头到响应
    nextResponse.headers.set('Access-Control-Allow-Origin', '*')
    nextResponse.headers.set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
    nextResponse.headers.set('Access-Control-Allow-Headers', 'Content-Type, Authorization')
    
    // 复制其他响应头
    if (response.headers) {
      response.headers.forEach((value, key) => {
        const excludeHeaders = ['content-length', 'content-encoding', 'transfer-encoding']
        if (!excludeHeaders.includes(key.toLowerCase())) {
          nextResponse.headers.set(key, value)
        }
      })
    }

    return nextResponse

  } catch (error) {
    console.error('[API Proxy] Error:', error)
    
    // 在开发环境下，如果后端不可用，返回模拟响应
    if (process.env.NODE_ENV === 'development') {
      console.log('[API Proxy] 使用模拟响应')
      return handleMockResponse(request, { params })
    }
    
    return NextResponse.json(
      { 
        error: '后端服务不可用', 
        message: error instanceof Error ? error.message : '未知错误',
        details: process.env.NODE_ENV === 'development' ? String(error) : undefined
      },
      { status: 500 }
    )
  }
}

// 处理模拟响应
async function handleMockResponse(
  request: NextRequest,
  { params }: { params: { path: string[] } }
) {
  try {
    if (!params || !Array.isArray(params.path)) {
      return NextResponse.json({ error: '无效的路径' }, { status: 400 })
    }

    const path = params.path.join('/')
    
    console.log(`[API Proxy] Mock response for: ${path}`)

    if (path === 'login' && request.method === 'POST') {
      try {
        const bodyText = await request.text()
        console.log('[API Proxy] 模拟登录请求体:', bodyText)
        
        const body = bodyText ? JSON.parse(bodyText) : {}
        const { username, password } = body
        
        console.log('[API Proxy] 模拟登录验证:', { username, password })
        
        if (username === 'admin' && password === 'admin123') {
          const successResponse = {
            success: true,
            token: 'mock-jwt-token-' + Date.now(),
            user: {
              id: 1,
              username: 'admin',
              email: 'admin@entrepreneur-home.com',
              nickname: '超级管理员',
              role: 'admin'
            }
          }
          console.log('[API Proxy] 模拟登录成功响应:', successResponse)
          return NextResponse.json(successResponse)
        } else {
          const errorResponse = {
            success: false,
            message: '用户名或密码错误'
          }
          console.log('[API Proxy] 模拟登录失败响应:', errorResponse)
          return NextResponse.json(errorResponse, { status: 401 })
        }
      } catch (parseError) {
        console.error('[API Proxy] Mock login parse error:', parseError)
        return NextResponse.json({
          success: false,
          message: '请求格式错误'
        }, { status: 400 })
      }
    }

    // Token验证模拟
    if (path === 'validate' && request.method === 'POST') {
      const authHeader = request.headers.get('authorization')
      const token = authHeader?.replace('Bearer ', '')
      
      console.log('[API Proxy] Token验证:', { token: token?.substring(0, 20) + '...' })
      
      if (token && token.startsWith('mock-jwt-token-')) {
        return NextResponse.json({ valid: true })
      } else {
        return NextResponse.json({ valid: false }, { status: 401 })
      }
    }

    // 用户信息获取模拟
    if (path === 'me' && request.method === 'GET') {
      const authHeader = request.headers.get('authorization')
      const token = authHeader?.replace('Bearer ', '')
      
      console.log('[API Proxy] 获取用户信息:', { token: token?.substring(0, 20) + '...' })
      
      if (token && token.startsWith('mock-jwt-token-')) {
        const userResponse = {
          user: {
            id: 1,
            username: 'admin',
            email: 'admin@entrepreneur-home.com',
            nickname: '超级管理员',
            role: 'admin'
          }
        }
        return NextResponse.json(userResponse)
      } else {
        return NextResponse.json({ error: '未授权' }, { status: 401 })
      }
    }

    // 注销模拟
    if (path === 'logout' && request.method === 'POST') {
      console.log('[API Proxy] 用户注销')
      return NextResponse.json({ message: '注销成功' })
    }

    // 仪表板统计数据模拟
    if (path === 'stats' && request.method === 'GET') {
      console.log('[API Proxy] 获取仪表板统计数据')
      const mockStats = {
        totalUsers: 1284,
        activeUsers: 456,
        totalNews: 89,
        totalPlans: 234,
        todayRegistrations: 12,
        todayLogins: 89
      }
      return NextResponse.json(mockStats)
    }

    // 用户列表模拟
    if (path === 'users' && request.method === 'GET') {
      console.log('[API Proxy] 获取用户列表')
      const mockUsers = []
      for (let i = 1; i <= 50; i++) {
        mockUsers.push({
          id: i,
          username: `user${i}`,
          email: `user${i}@example.com`,
          name: `用户${i}`,
          company: i % 3 === 0 ? `公司${i}` : null,
          status: Math.random() > 0.2 ? 1 : 0,
          createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
          lastLoginTime: Math.random() > 0.3 ? new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString() : null
        })
      }
      return NextResponse.json(mockUsers)
    }

    // 最近用户模拟
    if (path.startsWith('users/recent') && request.method === 'GET') {
      console.log('[API Proxy] 获取最近用户')
      const url = new URL(request.url)
      const limit = parseInt(url.searchParams.get('limit') || '5')
      
      const mockRecentUsers = [
        {
          id: 1,
          username: 'zhangsan',
          email: 'zhangsan@example.com',
          name: '张三',
          company: '创新科技有限公司',
          status: 1,
          createdAt: new Date('2025-01-15').toISOString(),
          lastLoginTime: new Date('2025-01-15T10:30:00').toISOString()
        },
        {
          id: 2,
          username: 'lisi',
          email: 'lisi@example.com',
          name: '李四',
          company: '未来创业公司',
          status: 1,
          createdAt: new Date('2025-01-14').toISOString(),
          lastLoginTime: new Date('2025-01-14T15:20:00').toISOString()
        },
        {
          id: 3,
          username: 'wangwu',
          email: 'wangwu@example.com',
          name: '王五',
          company: null,
          status: 0,
          createdAt: new Date('2025-01-13').toISOString(),
          lastLoginTime: null
        },
        {
          id: 4,
          username: 'zhaoliu',
          email: 'zhaoliu@example.com',
          name: '赵六',
          company: '智能设备公司',
          status: 1,
          createdAt: new Date('2025-01-12').toISOString(),
          lastLoginTime: new Date('2025-01-12T09:15:00').toISOString()
        },
        {
          id: 5,
          username: 'qianqi',
          email: 'qianqi@example.com',
          name: '钱七',
          company: null,
          status: 1,
          createdAt: new Date('2025-01-11').toISOString(),
          lastLoginTime: new Date('2025-01-11T14:30:00').toISOString()
        }
      ]
      
      return NextResponse.json(mockRecentUsers.slice(0, limit))
    }

    // 管理员列表模拟
    if (path === 'admins' && request.method === 'GET') {
      console.log('[API Proxy] 获取管理员列表')
      const mockAdmins = [
        {
          id: 1,
          username: 'admin',
          email: 'admin@entrepreneur-home.com',
          nickname: '超级管理员',
          status: 1,
          loginCount: 156,
          lastLoginTime: new Date().toISOString(),
          createdAt: new Date('2024-01-01').toISOString()
        },
        {
          id: 2,
          username: 'manager',
          email: 'manager@entrepreneur-home.com',
          nickname: '内容管理员',
          status: 1,
          loginCount: 89,
          lastLoginTime: new Date(Date.now() - 2 * 60 * 60 * 1000).toISOString(),
          createdAt: new Date('2024-02-15').toISOString()
        },
        {
          id: 3,
          username: 'editor',
          email: 'editor@entrepreneur-home.com',
          nickname: '编辑员',
          status: 0,
          loginCount: 45,
          lastLoginTime: new Date(Date.now() - 24 * 60 * 60 * 1000).toISOString(),
          createdAt: new Date('2024-03-10').toISOString()
        }
      ]
      return NextResponse.json(mockAdmins)
    }

    // 新闻列表模拟
    if (path === 'news' && request.method === 'GET') {
      console.log('[API Proxy] 获取新闻列表')
      const mockNews = []
      for (let i = 1; i <= 20; i++) {
        mockNews.push({
          id: `news_${i}`,
          title: `创业资讯标题 ${i}`,
          content: `这是第${i}篇创业资讯的详细内容...`,
          summary: `这是第${i}篇创业资讯的摘要`,
          category: ['startup', 'funding', 'policy', 'tech'][i % 4],
          status: ['draft', 'published', 'archived'][Math.floor(Math.random() * 3)],
          tags: [`标签${i}`, '创业'],
          authorId: 1,
          authorName: '管理员',
          publishedAt: Math.random() > 0.5 ? new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString() : null,
          createdAt: new Date(Date.now() - Math.random() * 30 * 24 * 60 * 60 * 1000).toISOString(),
          updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString(),
          views: Math.floor(Math.random() * 10000),
          likes: Math.floor(Math.random() * 1000),
          comments: Math.floor(Math.random() * 100)
        })
      }
      return NextResponse.json(mockNews)
    }

    // 商业计划书列表模拟
    if (path === 'business-plans' && request.method === 'GET') {
      console.log('[API Proxy] 获取商业计划书列表')
      const mockPlans = []
      for (let i = 1; i <= 15; i++) {
        mockPlans.push({
          id: `plan_${i}`,
          title: `商业计划书 ${i}`,
          industry: ['科技', '餐饮', '教育', '医疗', '金融'][i % 5],
          stage: ['创意阶段', '初创阶段', '成长阶段'][i % 3],
          description: `这是第${i}个商业计划书的描述`,
          authorId: i,
          authorName: `用户${i}`,
          status: ['draft', 'completed', 'reviewed'][Math.floor(Math.random() * 3)],
          createdAt: new Date(Date.now() - Math.random() * 60 * 24 * 60 * 60 * 1000).toISOString(),
          updatedAt: new Date(Date.now() - Math.random() * 7 * 24 * 60 * 60 * 1000).toISOString()
        })
      }
      return NextResponse.json(mockPlans)
    }

    // 其他路径的模拟响应
    console.log(`[API Proxy] 未处理的路径: ${path}`)
    return NextResponse.json({
      message: '模拟数据，请启动后端服务获取真实数据',
      path: path,
      data: []
    })

  } catch (error) {
    console.error('[API Proxy] Mock response error:', error)
    return NextResponse.json(
      { error: '模拟响应失败' },
      { status: 500 }
    )
  }
}

// 导出所有HTTP方法
export const GET = handleRequest
export const POST = handleRequest
export const PUT = handleRequest
export const DELETE = handleRequest
export const PATCH = handleRequest

// 处理OPTIONS请求（CORS预检）
export async function OPTIONS(request: NextRequest) {
  console.log('[API Proxy] 处理OPTIONS请求')
  return new NextResponse(null, {
    status: 200,
    headers: {
      'Access-Control-Allow-Origin': '*',
      'Access-Control-Allow-Methods': 'GET, POST, PUT, DELETE, OPTIONS',
      'Access-Control-Allow-Headers': 'Content-Type, Authorization',
      'Access-Control-Max-Age': '86400',
    },
  })
}